﻿using System.Web.UI;
using System.Web.UI.WebControls;
using System.Reflection;

namespace SlamCms.Common
{
	public static class PageExtensions
	{
		public static void BindControls(this Page page)
		{
			BindControlsRecursively(page);
		}

		public static void BindControlsRecursively(Control control)
		{
			foreach (Control subControl in control.Controls)
			{
				if (subControl is UserControl || subControl is WebControl)
				{
					AttributeCollection attributes = subControl.GetType().GetProperty("Attributes", BindingFlags.Instance | BindingFlags.Public).GetValue(subControl, null) as AttributeCollection;

					if (attributes["BindControl"] != null && attributes["BindControl"].Trim().ToUpper() == "TRUE")
					{
						subControl.GetType().GetMethod("DataBind", BindingFlags.Instance | BindingFlags.Public).Invoke(subControl, null);
					}
				}
				if (subControl.Controls.Count > 0) BindControlsRecursively(subControl);
			}
		}
	}
}
